<?php

class Categories extends Admin_Controller {

    public function __construct() {
        parent::__construct();
        
        $this->load->model('categories_m');
    }

    /**
     * Default function
     */
    public function index() {
        
    }

    /**
     * Create new categories
     */
    public function create() {
    }

    /**
     * Create method, creates a new category via ajax
     * @access public
     * @return void
     */
    public function create_ajax() {
        //Set response default
        $response = array(
            'error' => 1,
            'message' => 'Error Message'
        );
        
        if ($this->input->post()) {
            
            //Set array params
            $arrParams = array(
                'parent_id' => $this->input->post('parentId')?$this->input->post('parentId'):0,
                'title' => $this->input->post('name'),
                'slug' => $this->removeUnicode($this->input->post('name')),
                'info' => $this->input->post('info')
            );
            
            //Check title
            if ($this->categories_m->check_title($arrParams['title']))
            {
                $response['message'] = sprintf('Chuyên mục "%s" đã tồn tại.', $arrParams['title']);
                //Return response
                echo json_encode($response); exit;
            }
            
            //Insert categories
            $id = $this->categories_m->insert_ajax($arrParams);

            //Check result
            if ($id > 0) {
                $response['error'] = 0;
                $response['message'] = 'Chuyên mục đã được thêm.';
                $response['id'] = $id;
            } else {
                $response['message'] = 'Có lỗi xảy ra.';
            }
        }
        
        //Return response
        echo json_encode($response); exit;
    }

}